package com.ggboy.item_bank.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.ggboy.item_bank.controller.UserRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

@Configuration
public class ShiroCnofig {
    /**
     * 创建ShiroFilterFactoryBean
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean filter = new ShiroFilterFactoryBean();
        filter.setSecurityManager(securityManager);

        HashMap<String, String> filterMap = new HashMap<>();
        filterMap.put("/","anon");
//        filterMap.put("/index.html","anon");
        filterMap.put("/user/login","anon");
        filterMap.put("/register","anon");
        filterMap.put("/login.html","anon");
        filterMap.put("/register.html","anon");
        filterMap.put("/static/**","anon");
        filterMap.put("/user/sendMsg","anon");
        filterMap.put("/user/checkPhoneNum","anon");
        filterMap.put("/user/register","anon");
        filterMap.put("/**","authc");//需要先经过认证才可以访问
        filterMap.put("/index.html","perms[user:add]");//设置授权

        filter.setFilterChainDefinitionMap(filterMap);
        filter.setLoginUrl("/login.html");
        filter.setUnauthorizedUrl("/login.html");


        return filter;
    }

    /**
     * 创建DefaultWebSecurityManager
     */
    @Bean(name="securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联realm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    /**
     * 创建Realm
     */
    @Bean(name="userRealm")
    public UserRealm getRealm(){
        return new UserRealm();
    }

    @Bean
    public ShiroDialect getShiroDialect(){//用来整合shiro thymeleaf
        return new ShiroDialect();
    }
}
